<template>
  <div class="noticeBox">
    <q-btn
      round
      flat
      size="sm"
      color="white"
      icon="notifications_none"
      @click="openMessage"
    >
      <q-badge
        color="negative"
        style="padding: 2px 4px"
        title-color="white"
        floating
        v-if="noticeInfo.total > 0"
        >{{ noticeInfo.total }}
      </q-badge>
    </q-btn>
    <div>
      <q-menu
        :offset="[0, 15]"
        transition-show="jump-down"
        transition-hide="jump-up"
        max-height="800px"
        v-model="showMessage"
        :style="{ width: '400px' }"
      >
        <div>
          <q-card class="full-width">
            <q-tabs
              v-model="messageTab"
              class="text-grey"
              active-color="primary"
              indicator-color="primary"
              align="justify"
              narrow-indicator
            >
              <q-tab name="informs">
                <span>
                  {{
                    noticeInfo.informCount > 0
                      ? '通知' + '(' + noticeInfo.informCount + ')'
                      : '通知'
                  }}
                </span>
              </q-tab>
              <q-tab name="notifies">
                <span>
                  {{
                    noticeInfo.notifiesCount > 0
                      ? '消息' + '(' + noticeInfo.notifiesCount + ')'
                      : '消息'
                  }}
                </span>
              </q-tab>
              <q-tab name="waitDeals">
                <span>
                  {{
                    noticeInfo.waitDealCount > 0
                      ? '待办' + '(' + noticeInfo.waitDealCount + ')'
                      : '待办'
                  }}
                </span>
              </q-tab>
            </q-tabs>
            <q-separator />
            <q-tab-panels v-model="messageTab" animated>
              <q-tab-panel name="informs" class="q-pa-none">
                <q-list>
                  <q-scroll-area
                    :thumb-style="thumbStyle"
                    :bar-style="barStyle"
                    style="height: 380px"
                    class="col"
                    ref="secondRef"
                    @scroll="onScrollSecond"
                  >
                    <div
                      v-for="(inform, index) in noticeInfo.informs"
                      v-bind:key="index"
                      @click="look('informs', inform.id)"
                    >
                      <q-item class="cursor-pointer q-ma-xs">
                        <q-item-section avatar>
                          <q-avatar
                            color="orange"
                            text-color="white"
                            icon="email"
                          />
                        </q-item-section>
                        <q-item-section class="q-gutter-xs">
                          <q-item-label :lines="1" class="space">
                            {{ inform.title }}
                          </q-item-label>
                          <q-item-label caption :lines="1" class="space">
                            {{ inform.content }}
                          </q-item-label>
                        </q-item-section>
                        <q-btn
                          flat
                          round
                          dense
                          class="q-mx-xs"
                          color="negative"
                          icon="priority_high"
                          size="sm"
                          v-if="inform.state == 0"
                        />
                        <q-btn
                          flat
                          round
                          dense
                          class="q-mx-xs"
                          color="primary"
                          icon="delete"
                          size="md"
                          @click.stop="deleteInform('informs', inform.id)"
                        />
                      </q-item>
                      <q-separator
                        v-if="index < noticeInfo.informs.length - 1"
                        inset="item"
                      />
                    </div>
                    <div style="text-align: center" v-if="loading">
                      <q-circular-progress
                        indeterminate
                        size="25px"
                        color="orange"
                        class="q-ma-md"
                      />
                    </div>
                    <q-item-label
                      caption
                      :lines="1"
                      :class="
                        noticeInfo.informs.length == 0 ? 'nomorePlus' : 'nomore'
                      "
                      v-if="noMore || noticeInfo.informs.length == 0"
                    >
                      暂无更多</q-item-label
                    >
                  </q-scroll-area>

                  <q-separator />
                  <q-item class="row q-pa-none text-center cursor-pointer">
                    <!-- <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="清空通知"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="clearMessage('informs')"
                      ></q-btn>
                    </q-item-section> -->
                    <q-separator vertical />
                    <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="查看更多"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="lookMore()"
                      ></q-btn>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-tab-panel>
              <q-tab-panel name="notifies" class="q-pa-none">
                <q-list>
                  <div
                    v-for="(notify, index) in noticeInfo.notifies"
                    v-bind:key="index"
                    @click="look('notify', index)"
                  >
                    <q-item class="cursor-pointer q-ma-xs">
                      <q-item-section avatar>
                        <q-avatar
                          color="orange"
                          text-color="white"
                          icon="email"
                        />
                      </q-item-section>
                      <q-item-section class="q-gutter-xs">
                        <q-item-label :lines="1">
                          {{ notify.title }}
                        </q-item-label>
                        <q-item-label caption :lines="1">
                          {{ notify.content }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-separator
                      v-if="index < noticeInfo.informs.length - 1"
                      inset="item"
                    />
                  </div>
                  <q-item-label
                    caption
                    :lines="1"
                    style="text-align: center; padding: 10px 0; margin: 10px 0"
                    v-if="noticeInfo.notifies.length == 0"
                  >
                    暂无更多</q-item-label
                  >
                  <q-separator />
                  <q-item class="row q-pa-none text-center cursor-pointer">
                    <!-- <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="清空通知"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="clearMessage('notifies')"
                      ></q-btn>
                    </q-item-section> -->
                    <q-separator vertical />
                    <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="查看更多"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="lookMore()"
                      ></q-btn>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-tab-panel>
              <q-tab-panel name="waitDeals" class="q-pa-none">
                <q-list>
                  <div
                    v-for="(waitDeal, index) in noticeInfo.waitDeals"
                    v-bind:key="index"
                    @click="look('waitDeal', index)"
                  >
                    <q-item class="cursor-pointer q-ma-xs">
                      <q-item-section avatar>
                        <q-avatar
                          color="orange"
                          text-color="white"
                          icon="email"
                        />
                      </q-item-section>
                      <q-item-section class="q-gutter-xs">
                        <q-item-label :lines="1">
                          {{ waitDeal.title }}
                        </q-item-label>
                        <q-item-label caption :lines="1">
                          {{ waitDeal.content }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-separator
                      v-if="
                        noticeInfo.informs.length > 0 &&
                        index < noticeInfo.informs.length - 1
                      "
                      inset="item"
                    />
                  </div>
                  <q-item-label
                    caption
                    :lines="1"
                    style="text-align: center; padding: 10px 0; margin: 10px 0"
                    v-if="noticeInfo.notifies.length == 0"
                  >
                    暂无更多</q-item-label
                  >
                  <q-separator />

                  <q-item class="row q-pa-none text-center cursor-pointer">
                    <!-- <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="清空通知"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="clearMessage('waitDeals')"
                      ></q-btn>
                    </q-item-section> -->
                    <q-separator vertical />
                    <q-item-section class="col q-pa-none q-ma-none">
                      <q-btn
                        label="查看更多"
                        flat
                        :ripple="{ color: 'info' }"
                        class="q-ma-none full-width full-height no-border-radius"
                        @click="lookMore()"
                      ></q-btn>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-tab-panel>
            </q-tab-panels>
          </q-card>
        </div>
      </q-menu>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  notificationList,
  notificationUnread,
  notificationDetail,
  notificationDelete,
} from '@/api/basic';
import { useQuasar } from 'quasar';
import { createSocket, oncloseWS } from '@/utils/socket/socket';

const emit = defineEmits([]);
const thumbStyle = {
  right: '3px',
  borderRadius: '7px',
  backgroundColor: '#027be3',
  width: '4px',
  opacity: 0.75,
};
const barStyle = {
  right: '2px',
  borderRadius: '9px',
  backgroundColor: '#027be3',
  width: '6px',
  opacity: 0.2,
};
const noticeInfo: any = ref({
  total: 0, //总通知数
  informCount: 4, //通知数
  notifiesCount: 0, //消息数
  waitDealCount: 0, //待办数
  informs: [], //通知列表
  notifies: [], //消息列表
  waitDeals: [], //待办列表
});
const noticePage = ref({
  page: 1, //页码
  per_page: 6, //每页显示条数
  rowsNumber: 0, //总条数
  rowsPerPage: 6, //每页显示条数
});
const onScrollboolean = ref(false);
const notificationListNum = ref(1);

const loading = ref(false);
const noMore = ref(false);
const secondRef = ref();
const $q = useQuasar();

const data = reactive({
  showMessage: false,
  messageTab: 'informs',
});
const { showMessage, messageTab } = toRefs(data);

//创建socket
createSocket();
// 事件监听  如果websockte有反应触发"this.getDataFunc"方法
onMounted(() => {
  //发送数据
  // setTimeout(() => {
  //   sendWSPush({
  //     action: 'back/notify/push',
  //     body: {
  //       user_id: 16,
  //       type: 0,
  //       title: '推个送',
  //       content: '这是内容',
  //       state: 0,
  //       is_top: 0,
  //     },
  //   });
  // }, 5000);
  window.addEventListener('onmessageWS', getDataFunc);
});

const getDataFunc = (e: any) => {
  const data = JSON.parse(e.detail.data.data);
  console.log('onmessageWS', data);
  if (data.code == 200 && data.receiveType == 1) {
    getNotificationList();
    $q.notify({
      color: 'primary',
      group: false,
      icon: 'check_circle',
      position: 'bottom-right',
      multiLine: true,
      message: data.msg,
      actions: [
        {
          label: '查看',
          color: 'yellow',
          handler: () => {
            /* console.log('wooow') */
            showMessage.value = true;
          },
        },
        {
          label: '关闭',
          color: 'white',
          handler: () => {
            /* console.log('wooow') */
          },
        },
      ],
    });
  }
};

//通知列表
const getNotificationList = async () => {
  noMore.value = false;
  noticePage.value.page = 1;
  const resNum: any = await notificationUnread();
  console.log('通知数量', resNum);
  noticeInfo.value.total = resNum.data.num;
  const res: any = await notificationList(noticePage.value);
  notificationListNum.value = res.data.last_page;
  console.log('通知列表', res);
  noticeInfo.value.informs = res.data.data;
};
//通知数量
const getNotificationNum = async () => {
  const resNum: any = await notificationUnread();
  console.log('通知数量', resNum);
  noticeInfo.value.total = resNum.data.num;
};
getNotificationList();

const openMessage = () => {
  console.log('openMessage');
  showMessage.value = true;
};
const look = (type: any, index: any) => {
  console.log('点击列表', type, index);
  if (type === 'informs') {
    informLook(index);
    // informs[index].disable = true;
  } else if (type === 'notify') {
    // notifies[index].disable = true;
  } else {
    // waitDeals[index].disable = true;
  }
};
const deleteInform = (type: any, index: any) => {
  console.log('删除通知', index);
  if (type === 'informs') {
    console.log('位置', secondRef.value.getScrollPosition());
    secondRef.value.setScrollPosition('vertical', 0);
    deleteInformIndex(index);
  } else if (type === 'notify') {
  } else {
  }
};
const lookMore = () => {
  console.log('查看更多');
};
const clearMessage = (type: any) => {
  console.log('清空消息', type);
  if (type === 'informs') {
  } else if (type === 'notifies') {
  } else {
  }
};
//列表滚动到底部时触发
const onScrollSecond = (e: any) => {
  if (e.verticalPercentage >= 1) {
    console.log('滚动到底部', e);
    onScroll();
  }
};

//列表滚动到底部时触发
const onScroll = async () => {
  if (noMore.value || notificationListNum.value == noticePage.value.page) {
    loading.value = false;
    noMore.value = true;
    return;
  }

  //触底只执行一次开关
  loading.value = true;
  if (!onScrollboolean.value) {
    onScrollboolean.value = true;
    noticePage.value.page++;
    const res: any = await notificationList(noticePage.value);
    console.log('通知列表', res);
    noticeInfo.value.informs = [...noticeInfo.value.informs, ...res.data.data];
    loading.value = false;
    onScrollboolean.value = false;
    if (noticePage.value.page == res.data.last_page) {
      noMore.value = true;
    }
  }
};

//查看通知详情
const informLook = async (item: any) => {
  console.log('查看通知详情', item);
  $q.notify({
    progress: true,
    color: 'primary',
    group: false,
    icon: 'check_circle',
    position: 'top',
    timeout: 2000,
    message: '查看通知详情',
  });
  noticeInfo.value.informs.forEach((items: any) => {
    if (items.id == item) {
      if (items.state != 1) {
        noticeInfo.value.total--;
        items.state = 1;
        // await getNotificationNum();
      }
    }
  });
  //查看详情
  await notificationDetail({ id: item });
};

//删除单个通知
const deleteInformIndex = async (item: any) => {
  console.log('删除通知2222222', item);
  // notice.value.informs.forEach((items: any, indexs: any) => {
  //   if (items.id == item) {
  //     notice.value.informs.splice(indexs, 1);
  //   }
  // });
  const res: any = await notificationDelete({ id: [item] });
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
  }
  await getNotificationList();
};

onUnmounted(() => {
  console.log('销毁');
  //销毁事件监听(不然会创建多个监听事件，发一次通告提示好几次)
  window.removeEventListener('onmessageWS', getDataFunc);
  oncloseWS();
});

defineExpose({ loading, noMore, showMessage });
</script>
<style scoped lang="scss">
.noticeBox {
  margin-right: 5px;
}
.space {
  width: 200px;
}
.nomore {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px;
}
.nomorePlus {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 380px;
}
</style>
